package com.ia.aistream.controller.usertest;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSONObject;
import com.ia.aistream.common.annotation.Log;
import com.ia.aistream.common.exception.job.TaskException;
import com.ia.aistream.manager.framework.config.properties.ShiroConf;
import com.ia.aistream.manager.framework.notification.IEmailManager;
import com.ia.aistream.manager.framework.redis.RedisManager;
import com.ia.aistream.manager.framework.util.ShiroUtils;
import com.ia.aistream.manager.quartz.ISysJobManager;
import com.ia.aistream.mapper.quartz.SysJobMapper;
import com.ia.aistream.model.quartz.constant.SysJobConstants;
import com.ia.aistream.model.quartz.entity.SysJob;
import com.ia.aistream.model.system.entity.SysUser;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ia.aistream.common.enums.BusinessType;
import com.ia.aistream.model.usertest.entity.Userinfo;
import com.ia.aistream.service.usertest.IUserinfoService;
import com.ia.aistream.common.core.controller.BaseController;
import com.ia.aistream.common.core.domain.AjaxResult;
import com.ia.aistream.common.utils.poi.ExcelUtil;
import com.ia.aistream.common.core.page.TableDataInfo;

/**
 * 用户信息测试Controller
 * 
 * @author aistream
 * @date 2020-11-30
 */
@Controller
@RequestMapping("/usertest/userinfo")
public class UserinfoController extends BaseController
{
    private String prefix = "usertest/userinfo";

    @Autowired
    private SysJobMapper sysJobMapper;
    @Autowired
    private ISysJobManager sysJobManager;

    @Autowired
    private IUserinfoService userinfoService;

    @Autowired
    private IEmailManager emailManager;

    @Autowired
    private RedisManager redisManager;

    @RequiresPermissions("usertest:userinfo:view")
    @GetMapping()
    public String userinfo()
    {
        return prefix + "/userinfo";
    }

    /**
     * 查询用户信息测试列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Userinfo userinfo)
    {
        startPage();
        List<Userinfo> list = userinfoService.selectUserinfoList(userinfo);
        return getDataTable(list);
    }

    /**
     * 导出用户信息测试列表
     */
    @RequiresPermissions("usertest:userinfo:export")
    @Log(title = "用户信息测试", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Userinfo userinfo)
    {
        List<Userinfo> list = userinfoService.selectUserinfoList(userinfo);
        ExcelUtil<Userinfo> util = new ExcelUtil<Userinfo>(Userinfo.class);
        return util.exportExcel(list, "userinfo");
    }

    /**
     * 新增用户信息测试
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存用户信息测试
     */
    @RequiresPermissions("usertest:userinfo:add")
    @Log(title = "用户信息测试", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Userinfo userinfo)
    {
        return toAjax(userinfoService.insertUserinfo(userinfo));
    }

    /**
     * 修改用户信息测试
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        Userinfo userinfo = userinfoService.selectUserinfoById(id);
        mmap.put("userinfo", userinfo);
        return prefix + "/edit";
    }

    /**
     * 修改保存用户信息测试
     */
    @RequiresPermissions("usertest:userinfo:edit")
    @Log(title = "用户信息测试", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Userinfo userinfo)
    {
        return toAjax(userinfoService.updateUserinfo(userinfo));
    }

    /**
     * 删除用户信息测试
     */
    @RequiresPermissions("usertest:userinfo:remove")
    @Log(title = "用户信息测试", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(userinfoService.deleteUserinfoByIds(ids));
    }

    @ResponseBody
    @GetMapping("/insertJob")
    public AjaxResult insertJob() throws Exception{
        this.initJob("定时Demo","hl_aistream","com.ia.aistream.controller.usertest.QuartzDemoMethod.printA()","0/3 * * * * ?");
        return AjaxResult.success();
    }

    @ResponseBody
    @GetMapping("/chache")
    public AjaxResult chache(){
        SysUser user = ShiroUtils.getSysUser();
        return AjaxResult.success(user);
    }

    @ResponseBody
    @GetMapping("/updateJob")
    public AjaxResult updateJob() throws Exception{
        //this.initJob("定时Demo","hl_aistream","com.ia.aistream.controller.usertest.QuartzDemoMethod.printA()","0/3 * * * * ?");
        SysJob job = new SysJob();
        job.setJobId(5L);
        job.setJobName("定时Demo-new");
        job.setJobGroup("hl_aistream");
        job.setCronExpression("0/5 * * * * ?");
        job.setInvokeTarget("com.ia.aistream.controller.usertest.QuartzDemoMethod.printA()");
        sysJobManager.updateJob(job);
        return AjaxResult.success();
    }

    @ResponseBody
    @GetMapping("/deleteJob")
    public AjaxResult deleteJob() throws Exception{
        //this.initJob("定时Demo","hl_aistream","com.ia.aistream.controller.usertest.QuartzDemoMethod.printA()","0/3 * * * * ?");
        SysJob job = new SysJob();
        job.setJobId(5L);
        job.setJobName("定时Demo-del");
        job.setJobGroup("hl_aistream");
        sysJobManager.deleteJob(job);
        return AjaxResult.success();
    }

    /**
     * 暂停
     * @return
     * @throws Exception
     */
    @ResponseBody
    @GetMapping("/pauseJob")
    public AjaxResult pauseJob() throws Exception{
        //this.initJob("定时Demo","hl_aistream","com.ia.aistream.controller.usertest.QuartzDemoMethod.printA()","0/3 * * * * ?");
        SysJob job = new SysJob();
        job.setJobId(5L);
        job.setJobName("定时Demo-pause");
        job.setJobGroup("hl_aistream");
        sysJobManager.pauseJob(job);
        return AjaxResult.success();
    }

    /**
     * 重启
     * @return
     * @throws Exception
     */
    @ResponseBody
    @GetMapping("/resumeJob")
    public AjaxResult resumeJob() throws Exception{
        //this.initJob("定时Demo","hl_aistream","com.ia.aistream.controller.usertest.QuartzDemoMethod.printA()","0/3 * * * * ?");
        SysJob job = new SysJob();
        job.setJobId(5L);
        job.setJobName("定时Demo-resume");
        job.setJobGroup("hl_aistream");
        sysJobManager.resumeJob(job);
        return AjaxResult.success();
    }

    @ResponseBody
    @GetMapping("/sendMail")
    public AjaxResult sendMail() throws Exception{
        emailManager.sendSimpleMessage("18335102080@163.com","这是一个测试邮件","这是测试邮件内容");
        return AjaxResult.success();
    }

    @ResponseBody
    @GetMapping("/sendHTMLMail")
    public AjaxResult sendHTMLMail() throws Exception{
        emailManager.sendMimeMessage("18335102080@163.com","这是HTML类型测试邮件","<span><strong>Hi：</strong><span><br/><span>小明</span>");
        return AjaxResult.success();
    }

    @ResponseBody
    @GetMapping("/sendAttchMail")
    public AjaxResult sendAttchMail() throws Exception{
        emailManager.sendAttachmentsMail("18335102080@163.com","这是带附件的邮件","<span><strong>Hi：</strong><span><br/><span>附件小明</span>",
                "D:\\学习相关\\小说\\aaa.zip");
        return AjaxResult.success();
    }

    @ResponseBody
    @GetMapping("/redisSet")
    public AjaxResult redisSet() throws Exception{
        Userinfo userinfo = new Userinfo();
        userinfo.setId(1L);
        userinfo.setName("name1");
        userinfo.setSex("F");
        Userinfo userinfo1 = new Userinfo();
        userinfo1.setId(2L);
        userinfo1.setName("name2");
        userinfo1.setSex("F");
        List<Userinfo> list = new ArrayList<>();
        list.add(userinfo);
        list.add(userinfo1);
        redisManager.hset("infouser","userField",list);
        redisManager.expire("infouser",1L, TimeUnit.HOURS);
        return AjaxResult.success();
    }

    @ResponseBody
    @GetMapping("/redisGet")
    public AjaxResult redisGet() throws Exception{
        List<JSONObject> list = redisManager.hget("infouser","userField",List.class);
        for (JSONObject info : list){
            Userinfo u = JSONObject.toJavaObject(info,Userinfo.class);
            System.out.println(info.toString());
            System.out.println("u="+info.toString());
        }
        return AjaxResult.success(list);
    }

    private void initJob(String jobName, String jobGroup, String invokeTarget, String expression) throws TaskException, SchedulerException {
        Date current = new Date();
        SysJob job = new SysJob();

        job.setJobName(jobName);
        job.setJobGroup(jobGroup);
        job.setInvokeTarget(invokeTarget);
        job.setCronExpression(expression);
        job.setMisfirePolicy(SysJobConstants.MISFIRE_DEFAULT);
        job.setConcurrent("0");
        job.setStatus(SysJobConstants.Status.NORMAL.getValue());
        job.setUpdateTime(current);
        SysJob sysJob = sysJobMapper.selectCheckJob(jobName, jobGroup);
        if (sysJob == null) {
            job.setCreateTime(current);
            sysJobManager.insertJob(job);
            sysJobManager.resumeJob(job);
        } else {
            job.setJobId(sysJob.getJobId());
            sysJobManager.updateJob(job);
        }
    }
}
